package com.tron.dobest.java.tronthread;

public class UserGateThread extends Thread{

    private final Gate gate;
    private final String name;
    private final String address;

    public UserGateThread(Gate gate, String name, String address) {
        this.gate = gate;
        this.name = name;
        this.address = address;
    }

    public static void main(String[] args) {
        Gate gate = new Gate();
        new UserGateThread(gate,"Alice", "Alaska").start();
        new UserGateThread(gate,"Bobby", "Brazil").start();
        new UserGateThread(gate,"Chris", "Canada").start();

    }

    /**
     * 线程方法调用gate pass方法，gate为公共资源。
     */
    @Override
    public void run() {
        while (true) {
            gate.pass(name,address);
        }
    }

    public static class Gate{
        private int counter = 0;
        private String name = "NoBody";
        private String address = "NoWhere";

        /**
         * 通过方法
         * @param name
         * @param address
         */
        public void pass(String name, String address) {
            this.name = name;
            this.address = address;
            counter++;
            check();
        }

        public String toString() {
            return "No." + counter + ": " + name + "," + address;
        }

        /**
         * 检查用户名和地址的首字母，如果不相等打印数据异常
         */
        private  void check() {
            if (name.charAt(0) != address.charAt(0)) {
                System.out.println("======BROKEN======"+toString());
            }
        }
    }
}
